package android.component;

import android.annotation.NonNull;
import android.life.viewmodel.HasDefaultViewModelProviderFactory;
import android.life.viewmodel.ViewModelProvider;
import android.life.viewmodel.ViewModelStore;
import android.life.viewmodel.ViewModelStoreOwner;
import android.log.Log;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.AbilitySlice;

/**
 * 模拟Android的Fragment，具有ViewModelStore,否则无法使用ViewModel的相关功能
 * 新的Android的库里的Fragment和Activity都是具有ViewModelStore的功能
 */
public class CompatSlice extends AbilitySlice implements
        ViewModelStoreOwner, HasDefaultViewModelProviderFactory {
    private ViewModelStore mViewModelStore;
    private ViewModelProvider.Factory mDefaultFactory;

    @Override
    @NonNull
    public ViewModelStore getmViewModelStore() {
        if (getAbility() == null) {
            throw new RuntimeException("you slice do not attach an ability");
        }
        if (mViewModelStore == null) {
            mViewModelStore = new ViewModelStore();
        }
        return mViewModelStore;
    }

    @Override
    public ViewModelProvider.Factory getDefaultViewModelProviderFactory() {
        if (getAbility() == null) {
            throw new IllegalStateException("Your activity is not yet attached to the "
                    + "Application instance. You can't request ViewModel before onCreate call.");
        }
        if (mDefaultFactory == null) {
            mDefaultFactory = ViewModelProvider.NewInstanceFactory.getInstance();
        }
        return mDefaultFactory;
    }

    @Override
    protected void onStop() {
        super.onStop();
        clearViewModelStore();
    }

    private void clearViewModelStore() {
        Ability ability = getAbility();
        boolean isChangingConfigurations = (mViewModelStore != null);

        if (ability instanceof CompatAbility) {
            isChangingConfigurations = isChangingConfigurations & ((CompatAbility) (ability)).isChangingConfigurations();
        }

        if (mViewModelStore != null && !isChangingConfigurations) {
            Log.d("ViewModelSlice clearViewModelStore in slice");
            mViewModelStore.clear();
        }
    }
}
